package org.hepeng.workx.monitor.linux;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.util.ExecUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author he peng
 */

@Slf4j
public class LoadAverageMonitor {

    public static LinuxLoadAverage getLoadAverage() {
        try {
            List<String> results = ExecUtils.exec("uptime");
            if (CollectionUtils.isNotEmpty(results)) {
                String result = results.get(0);
                //  10:08:52 up 90 days, 16:39,  3 users,  load average: 0.23, 0.18, 0.17
                String markStr = "load average:";
                if (StringUtils.contains(result , markStr)) {
                    int i = StringUtils.lastIndexOf(result, markStr);
                    String loadAverageStr = StringUtils.replace(StringUtils.substring(result, i + markStr.length()) , " " ,"");
                    String[] loadAverageArr = StringUtils.split(loadAverageStr, ",");
                    LinuxLoadAverage linuxLoadAverage = new LinuxLoadAverage();
                    linuxLoadAverage.setLoadAverageWithin1m(Double.valueOf(loadAverageArr[0]));
                    linuxLoadAverage.setLoadAverageWithin5m(Double.valueOf(loadAverageArr[1]));
                    linuxLoadAverage.setLoadAverageWithin15m(Double.valueOf(loadAverageArr[2]));
                    return linuxLoadAverage;
                }
            }
        } catch (IOException e) {
            log.error("exec [uptime] get linux os load average error" , e);
        }
        return null;
    }

    @Data
    public static class LinuxLoadAverage {
        private double loadAverageWithin1m;
        private double loadAverageWithin5m;
        private double loadAverageWithin15m;
    }
}
